import request from '../../utils/request'
import downloadFile from '../../utils/downloadFile'
import colorThief from "miniapp-color-thief";

Page({
  /**
   * 页面的初始数据
   */
  data: {
    palette: "[28, 48, 67]",

    userInfo: {}, // 用户信息
    userPlayList: [], // 用户歌单
    // recentPlayList: [] // 最近播放
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 读取用户信息
    let userInfo = wx.getStorageSync('userInfo')
    if (userInfo) {
      this.setData({ userInfo: JSON.parse(userInfo) })

      // 获取用户播放记录
      // this.getUserRecentPlayList(this.data.userInfo.userId)

      // 获取用户歌单
      this.getUserPlayList(this.data.userInfo.userId)

      // 获取主色调
      this.bgcDownload()
    }
  },

  // 获取用户歌单
  async getUserPlayList(uid) {
    let userPlayList = await request('/user/playlist', { uid })
    this.setData({ userPlayList: userPlayList.playlist })
  },

  // 获取用户播放记录的功能函数
  async getUserRecentPlayList(userId) {
    let recentPlayListData = await request('/user/record', { uid: userId, type: 0 });
    let recentPlayList = recentPlayListData.allData.splice(0, 10).map((item, index) => {
      item.id = index;
      return item;
    })
    this.setData({
      recentPlayList
    })
  },

  // 跳转到登录页
  toLogin() {
    wx.navigateTo({
      url: '/pages/login/login',
    })
  },

  // 跳转至recommendSong页面的回调
  toRecommendSong(e) {
    let id = e.currentTarget.dataset.id;
    let title = e.currentTarget.dataset.title;
    wx.navigateTo({
      url: `/pages/recommendSong/recommendSong?id=${id}&title=${title}`
    });
  },

  // 判断是否有背景图片的缓存文件，没有就下载为临时文件，最后绘画出来
  async bgcDownload() {
    let bgcUrl = wx.getStorageSync('bgcUrl')
    let result = await downloadFile(this.data.userInfo.backgroundUrl, bgcUrl, 'bgcUrl')
    console.log(result);

    const ctx = wx.createCanvasContext('myCanvas')
    ctx.drawImage(result, 0, 0, 300, 150);
    ctx.draw(false, () => {
      wx.canvasGetImageData({
        canvasId: "myCanvas",
        x: 0,
        y: 0,
        width: 300,
        height: 150,
        success: res => {
          let colorThiefArr = colorThief(res.data).palette(10).get()
          let palette = colorThiefArr.find(item => item[0] <= 150 && item[1] <= 150 && item[2] <= 150);
          console.log(palette);
          this.setData({ palette })
        }
      });
    })
  },

  onReady: function () {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})